package com.sgb.kjwl.view.widget.packers;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.sgb.kjwl.R;
import com.sgb.kjwl.interfaces.FragmentOnItemClick;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.adapter.packers.MemberCompanyAdapter;
import com.sgb.kjwl.view.ui.fragment.packers.TeamMainMenuFragment;
import com.sgb.kjwl.view.ui.fragment.packers.TeamMenuFragment;
import com.sgb.link.databinding.ItemRecyclerviewBinding;
import com.sgb.link.databinding.LayoutCountMenuViewNewBinding;
import com.sgb.link.entity.MenuEntity;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.FragPagerAdapter;
import com.swgk.core.util.ClickUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * 2020-12月-24日
 * 黄淋
 * 根据新ui显示的滑动菜单 用于满足物流金刚区来自后台配置的货物类型、车型
 */
public class TeamMenuView extends RelativeLayout {

    private Context mContext;
    private LayoutCountMenuViewNewBinding viewBinding;
    private ArrayList<Fragment> menuFragment = new ArrayList<>();
    private FragPagerAdapter menuAdapter;
    public int COLUMN_COUNT = 5; //一行多少个
    public int ROW_COUNT = 2; //一页多少行
    private int page = 1;
    private ImageView[] memuTip;

    public TeamMenuView(@NonNull Context context) {
        super(context);
        this.mContext = context;
        initView();
    }

    public TeamMenuView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        getInItData(attrs);
        initView();
    }

    public TeamMenuView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        getInItData(attrs);
        initView();
    }

    private void getInItData(@Nullable AttributeSet attrs) {
        TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.CountMenuView);
        ROW_COUNT = typedArray.getInt(R.styleable.CountMenuView_is_row, 2);
        COLUMN_COUNT = typedArray.getInt(R.styleable.CountMenuView_is_column, 5);
        typedArray.recycle();
    }

    /**
     * 布局初始化
     */
    private void initView() {
        viewBinding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.layout_count_menu_view_new, this, true);
    }

    /**
     * 设置栏目菜单显示的行数和列数
     *
     * @param row    一页多少行
     * @param column 一行多少个
     */
    public void setRowAndColumn(int row, int column) {
        this.ROW_COUNT = row;
        this.COLUMN_COUNT = column;
    }

    /**
     * 设置布局数据，计算需要显示的页数
     *
     * @param fm
     * @param datalist
     * @param onItemClick
     */
    public void initData(FragmentManager fm, List<AddressEntity> datalist, OnItemClick onItemClick) {
        if (menuFragment == null) {
            menuFragment = new ArrayList<>();
        }
        menuFragment.clear();
        int total = datalist.size();
        page = total % (COLUMN_COUNT * ROW_COUNT) > 0 ? total / (COLUMN_COUNT * ROW_COUNT) + 1 : total / (COLUMN_COUNT * ROW_COUNT);
        for (int i = 0; i < page; i++) {
            List<AddressEntity> menuEntityList = new ArrayList<>();
            int fir = i * COLUMN_COUNT * ROW_COUNT;
            int last = (i + 1) * COLUMN_COUNT * ROW_COUNT > total ? total : (i + 1) * COLUMN_COUNT * ROW_COUNT;
            menuEntityList.addAll(datalist.subList(fir, last));
            menuFragment.add(TeamMenuFragment.newInstance(menuEntityList, COLUMN_COUNT, ROW_COUNT, i));
            TeamMenuFragment big = (TeamMenuFragment) menuFragment.get(i);
            big.setOnItemClickCallBack(new TeamMenuFragment.OnItemClickCallBack() {

                @Override
                public void onClick(AddressEntity entity, int position, int num) {
                    if (!ClickUtils.isDoubleClick2()) {
                        if (onItemClick != null) {
                            onItemClick.onItemClick(entity, position, num);
                        }
                    }
                }
            });
        }
        initDataView(fm);
        if (page > 1) {
            viewBinding.dotMenuLayout.setVisibility(VISIBLE);
            viewBinding.dotMenuLayout.removeAllViews();
            initDotsMenu(0);
        } else {
            viewBinding.dotMenuLayout.removeAllViews();
            viewBinding.dotMenuLayout.setVisibility(GONE);
        }
    }

    /**
     * 设置布局数据，计算需要显示的页数
     *
     * @param fm
     * @param datalist
     * @param onItemClick
     */
    public void initData(FragmentManager fm, int count, int row, ArrayList<Fragment> mainMenuFragment, List<AddressEntity> datalist, OnItemClick onItemClick) {
        int total = datalist.size();
        page = total % (count * row) > 0 ? total / (count * row) + 1 : total / (count * row);
        for (int i = 0; i < page; i++) {
            TeamMainMenuFragment big = (TeamMainMenuFragment) mainMenuFragment.get(i);
            big.setOnItemClickCallBack(new FragmentOnItemClick() {
                @Override
                public void onClick(AddressEntity entity, int position, int num) {
                    if (!ClickUtils.isDoubleClick2()) {
                        if (onItemClick != null) {
                            onItemClick.onItemClick(entity, position, num);
                        }
                    }
                }
            });
        }
        initDataView1(fm, mainMenuFragment, page);
        if (page > 1) {
            viewBinding.dotMenuLayout.setVisibility(VISIBLE);
            viewBinding.dotMenuLayout.removeAllViews();
            initDotsMenu(0);
        } else {
            viewBinding.dotMenuLayout.removeAllViews();
            viewBinding.dotMenuLayout.setVisibility(GONE);
        }
    }

    public void initData(int count, int row, List<AddressEntity> datalist) {
        int total = datalist.size();
        page = total % (count * row) > 0 ? total / (count * row) + 1 : total / (count * row);
        List<View> views = new ArrayList<>();
        if (total == 0) {
            View view = LayoutInflater.from(mContext).inflate(com.sgb.kjwl.R.layout.item_recyclerview, null);
            ItemRecyclerviewBinding binding = DataBindingUtil.bind(view);
            binding.llEmpty.setVisibility(VISIBLE);
            binding.rlvHomeMenu.setVisibility(GONE);
            views.add(binding.flRoot);

        }else {
            for (int i = 0; i < page; i++) {
                int fir = i * count * row;
                int last = Math.min((i + 1) * count * row, total);
                List<AddressEntity> menuEntityList = new ArrayList<>(datalist.subList(fir, last));
                View view = LayoutInflater.from(mContext).inflate(com.sgb.kjwl.R.layout.item_recyclerview, null);
                ItemRecyclerviewBinding binding = DataBindingUtil.bind(view);
                binding.rlvHomeMenu.setLayoutManager(new GridLayoutManager(mContext, 3));
                MemberCompanyAdapter adapter = new MemberCompanyAdapter(mContext, null);
                binding.rlvHomeMenu.setAdapter(adapter);
                adapter.setDatas(menuEntityList);
                adapter.setOnItemClick(new AdapterOnItemClick<AddressEntity>() {
                    @Override
                    public void onItemClick(AddressEntity addressEntity, int position) {
                        WebsiteInfoActivity.start(mContext, addressEntity.getNo(), WebsiteInfoActivity.WEBSITE_FOR_COMPANY);
                    }
                });
                views.add(binding.flRoot);
            }
        }
        ViewPagerAdapter menuAdapter = new ViewPagerAdapter(mContext, views);
        viewBinding.consViewPage.setAdapter(menuAdapter);
        viewBinding.consViewPage.setOffscreenPageLimit(page);
        viewBinding.consViewPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                setImageBackgroundMenu(position % page);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        if (page > 1) {
            viewBinding.dotMenuLayout.setVisibility(VISIBLE);
            viewBinding.dotMenuLayout.removeAllViews();
            initDotsMenu1(0);
        } else {
            viewBinding.dotMenuLayout.removeAllViews();
            viewBinding.dotMenuLayout.setVisibility(GONE);
        }
    }

    public void setData(List<MenuEntity> dataList) {

    }

    /**
     * 将传入的数据显示在布局中
     *
     * @param fm
     */
    private void initDataView(FragmentManager fm) {
        menuAdapter = new FragPagerAdapter(fm, menuFragment);
        viewBinding.consViewPage.setAdapter(menuAdapter);
        viewBinding.consViewPage.setOffscreenPageLimit(page);
        viewBinding.consViewPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                setImageBackgroundMenu(position % page);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void initDataView1(FragmentManager fm, ArrayList<Fragment> fragments, int pages) {
        menuAdapter = new FragPagerAdapter(fm, fragments);
        viewBinding.consViewPage.setAdapter(menuAdapter);
        viewBinding.consViewPage.setOffscreenPageLimit(pages);
        viewBinding.consViewPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                setImageBackgroundMenu(position % pages);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    /**
     * 根据传入数据和当前设置的布局行列的出来的页数布局标识
     */
    private void initDotsMenu(int selectItems) {
//        if (memuTip != null){
//            memuTip.clone();
//        }
        memuTip = new ImageView[page];
        for (int i = 0; i < page; i++) {
            ImageView imageView = new ImageView(mContext);
            imageView.setBackgroundResource(R.drawable.select_banner_dot);
            memuTip[i] = imageView;
            float w = getResources().getDimension(R.dimen.dp8);
            if (i == selectItems) {
//                w = getResources().getDimension(R.dimen.dp8);
                memuTip[i].setSelected(true);
            } else {
//                w = getResources().getDimension(R.dimen.dp9);
                memuTip[i].setSelected(false);
            }
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams((int) w,
                    (int) getResources().getDimension(R.dimen.dp2)));
            layoutParams.leftMargin = (int) getResources().getDimension(R.dimen.dp1);
            layoutParams.rightMargin = (int) getResources().getDimension(R.dimen.dp1);
            viewBinding.dotMenuLayout.addView(imageView, layoutParams);
        }
    }

    private void initDotsMenu1(int selectItems) {
//        if (memuTip != null){
//            memuTip.clone();
//        }
        memuTip = new ImageView[page];
        for (int i = 0; i < page; i++) {
            ImageView imageView = new ImageView(mContext);
            imageView.setBackgroundResource(R.drawable.select_banner_dot_1);
            memuTip[i] = imageView;
            float w = getResources().getDimension(R.dimen.dp8);
            if (i == selectItems) {
//                w = getResources().getDimension(R.dimen.dp8);
                memuTip[i].setSelected(true);
            } else {
//                w = getResources().getDimension(R.dimen.dp9);
                memuTip[i].setSelected(false);
            }
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams((int) w,
                    (int) getResources().getDimension(R.dimen.dp2)));
            layoutParams.leftMargin = (int) getResources().getDimension(R.dimen.dp1);
            layoutParams.rightMargin = (int) getResources().getDimension(R.dimen.dp1);
            viewBinding.dotMenuLayout.addView(imageView, layoutParams);
        }
    }

    /**
     * 选中当前不的布局标识
     *
     * @param selectItems
     */
    private void setImageBackgroundMenu(int selectItems) {
//        viewBinding.dotMenuLayout.removeAllViews();
//        initDotsMenu(selectItems);
        for (int i = 0; i < memuTip.length; i++) {
            if (i == selectItems) {
                memuTip[i].setSelected(true);
            } else {
                memuTip[i].setSelected(false);
            }
        }
    }

    public void cleanAdapter() {
        menuAdapter = null;
    }

    public OnItemClick onItemClick;

    public void setOnItemClick(OnItemClick onItemClick) {
        this.onItemClick = onItemClick;
    }

    public static class OnItemClick {

        public void onItemClick(AddressEntity entity, int position, int num) {
        }
    }


    private class ViewPagerAdapter extends PagerAdapter {

        private final Context context;
        private List<View> data;

        public ViewPagerAdapter(Context context, List<View> data) {
            this.context = context;
            this.data = data;
        }

        @Override
        public int getCount() {
            return data == null ? 0 : data.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NotNull
        @Override
        public Object instantiateItem(@NotNull ViewGroup container, int position) {
            /*   ViewGroup parent=(ViewGroup)data.get(position).getParent();*/
            container.addView(data.get(position));
            return data.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, @NotNull Object object) {
            container.removeView((View) object);
        }

    }
}
